const express = require('express');
const multer = require('multer'); // 用于处理文件上传
const path = require('path');//获取当前地址模块
const app = express();
const PORT = process.env.PORT || 3000;

app.use('/imgUploads', express.static(path.join(__dirname, 'imgUploads')));// 设置静态文件目录

// 配置 multer 中间件来处理文件上传
const storage = multer.diskStorage({
    // 设置图片存储的位置
    destination: (req, file, cb) => {cb(null, './imgUploads');},
    // 设置图片的名字
    filename: (req, file, cb) => {
      // console.log('file',file)
      cb(null, file.originalname);
    },
});

const upload = multer({ storage });

//post 图片上传
app.post('/imgUpload', upload.single('image'), (request, response) => {
    const data = {
        message: '图片上传成功!',
        //图片的地址
    	url:`http://192.168.1.2:3000/imgUploads/${request.file.filename}` 
    }
    const visitorIP = request.headers['x-forwarded-for'] || request.connection.remoteAddress;
    console.log(data, '获取的请求参数');
    console.log(visitorIP, '请求者的地址');
    response.status(200).send(data)
})

// 启动服务器
app.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
});